package com.woniu.woniu_bx.utils;

import com.woniu.woniu_bx.pojo.Order;
import com.woniu.woniu_bx.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author sjy
 * @create 2022-08-29 11:25
 */

@Component
public class OrderOverTime {
    @Autowired
    private OrderService orderService;
    //等待确认的订单
    static List<Order> waitSureOrders;

    static List<Order> waitFinishOrders;

    /**
     * 每秒钟执行一次
     * 三天未确认则自动取消
     * 三天未确认收货则自动收货
     */
    @Scheduled(cron = "0/1 * * * * ?")
    public void overTime() {
        while (true) {
            try {
                String currentTime = GetCurrentTime.getCurrentTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                waitSureOrders = orderService.getWaitSureOrder();
                waitFinishOrders = orderService.getWaitFinishOrder();
                if(!waitSureOrders.isEmpty()){
                    //自动取消
                    for (Order waitSureOrder : waitSureOrders) {
                        Date buyTime = sdf.parse(waitSureOrder.getBuyTime());
                        Date time = sdf.parse(currentTime);
                        Long overTime = (time.getTime() - buyTime.getTime()) /1000;
                        Integer threeDay = 3 * 24 * 60 * 60;
                        if ((threeDay - overTime) <= 0) {
                            waitSureOrder.setPwOption("o");
                            waitSureOrder.setState("n");
                            orderService.updateById(waitSureOrder);
                        }
                    }
                }
                if(!waitFinishOrders.isEmpty()){
                    //自动确认收货
                    for (Order waitFinishOrder : waitFinishOrders) {
                        Date servedTime = sdf.parse(waitFinishOrder.getServedTime());
                        Date time = sdf.parse(currentTime);
                        Long overTime = (time.getTime() - servedTime.getTime()) /1000;
                        Integer threeDay = 3 * 24 * 60 * 60;
                        if ((threeDay - overTime) <= 0) {
                            waitFinishOrder.setState("5");
                            orderService.updateById(waitFinishOrder);
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
